package com.kongge.algorithm.demo;

/**
 * 输入一个整数数组，实现一个函数调整该数组中数字的顺序，使得所有奇数位于数组的前半部分，所有偶数位于数组的右半部分
 * 按条件重新排列数组
 * @author gaoshiqi
 *
 */
public class ReOrderArrByConditions implements IAlgorithm{

	public void execute() {
		int[] arr = {1, 4, 3, 5, 6, 8, 9};
		ICondition condition = new ConditionBeDivisibleBy3();
		reOrder(arr, condition);
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
	}

	private void reOrder(int[] arr, ICondition condition) {
		if (arr == null || arr.length == 0 || condition == null) {
			return;
		}
		int leftIndex = 0;
		int rightIndex = arr.length - 1;
		while (leftIndex < rightIndex) {
			while (condition.judgeCondition(arr[rightIndex]) && rightIndex > leftIndex) {
				rightIndex --;
			}
			while (!condition.judgeCondition(arr[leftIndex]) && leftIndex < rightIndex) {
				leftIndex ++;
			}
			if (leftIndex != rightIndex) {
				int temp = arr[leftIndex];
				arr[leftIndex] = arr[rightIndex];
				arr[rightIndex] = temp;
			}
		}
	}
	
	private interface ICondition {
		boolean judgeCondition(int number);
	}
	
	/**
	 * 判断是否是偶数
	 * @author gaoshiqi
	 *
	 */
	private class ConditionEvenNumber implements ICondition{
		public boolean judgeCondition(int number) {
			return (number & 0x01) == 0;
		}
	}
	
	/**
	 * 判断是否是正数
	 * @author gaoshiqi
	 *
	 */
	private class ConditionPositiveNumber implements ICondition{
		public boolean judgeCondition(int number) {
			return number > 0;
		}
	}
	
	/**
	 * 判断是否能被3整除
	 * @author gaoshiqi
	 *
	 */
	private class ConditionBeDivisibleBy3 implements ICondition{
		public boolean judgeCondition(int number) {
			return number % 3 == 0;
		}
	}
}
